package StudyCode.summary.mycollection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class AComprehensiveIsEqualMethodThatHandlesNullsAndArraysSafely {
	public static void main(String[] argv) {
		Object value = "www.tah1986.com";
		Object otherValue = "www.tah1986.com";
		System.out.println(areEqual(value, otherValue));
	}

	public static final boolean areEqual(Object value, Object otherValue) {
		if (value == otherValue)
			return true;
		if (value == null)
			return false;
		if (otherValue == null)
			return false;

		if (value.getClass().getComponentType() != null)
			return arraysAreEqual(value, otherValue);
		return value.equals(otherValue);
	}

	public static final boolean arraysAreEqual(Object value,
	                                           Object otherValue) {
		if (value instanceof Object[]) {
			if (otherValue instanceof Object[])
				return valuesAreTransitivelyEqual((Object[]) value,
						(Object[]) otherValue);
			return false;
		}
		return false;
	}

	public static final boolean valuesAreTransitivelyEqual(
			Object[] thisArray, Object[] thatArray) {
		if (thisArray == thatArray)
			return true;
		if ((thisArray == null) || (thatArray == null))
			return false;
		if (thisArray.length != thatArray.length)
			return false;
		for (int i = 0; i < thisArray.length; i++) {
			if (!areEqual(thisArray[i], thatArray[i]))
				return false;
		}
		return true;
	}
}
